package com.gxa.oauth;

import com.gxa.common.uitls.JwtUtils;
import com.gxa.entity.User;
import com.gxa.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 认证
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /*User user = (User) principals.getPrimaryPrincipal();
        Integer userId = user.getId();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;*/
        return null;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

       /* System.out.println("--------认证方法------");
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        String username = utoken.getUsername();

        //根据用户名查询 用户对象 ，shiro会自动完成比对工作
        User user = this.userMapper.queryByUserName(username);
        // System.out.println("查询到的user--------"+user);
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());

        //三个参数： 第一个参数：当前登录这个用户   第二个参数：从数据库中查询的密码 第三个参数：realm名字
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
        return authenticationInfo;*/




        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户的id
        //String userId = JwtUtils.getMemberIdByJwtToken(accessToken);
        String pwd = JwtUtils.getMemberPwdByJwtToken(accessToken);
        String userName = JwtUtils.getMemberUserNameByJwtToken(accessToken);

        //校验token是否存在与有效
        if(!JwtUtils.checkToken(accessToken)){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        User user = userMapper.queryByUserNameAndPwd(userName, pwd);

        //账号锁定
       /* if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }*/

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(accessToken, accessToken, getName());
        return info;
    }
}
